package com.qf.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAd;
import com.qf.pojo.DtsAdmin;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhaojian
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private DtsAdminMapper adminMapper;

    @Override
    public List<DtsAdmin> findAdminByUserName(String userName) {
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);

        List<DtsAdmin> list = adminMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public IPage<DtsAdmin> findByPage(Integer page, Integer limit, String username, String sort, String order) {
        //分页参数
        Page<DtsAdmin> adminPage = new Page<>(page,limit);
        //查询条件
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(username)){
            queryWrapper.like("username",username);
        }
        if ("asc".equalsIgnoreCase(order)){
            queryWrapper.orderByAsc(sort);
        }else{
            queryWrapper.orderByAsc(sort);
        }
        IPage<DtsAdmin> pageResult = adminMapper.selectPage(adminPage,queryWrapper);
        return pageResult;
    }

    @Override
    public DtsAdmin insertAdmin(DtsAdmin dtsAdmin) {
        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        dtsAdmin.setPassword(encoder.encode(dtsAdmin.getPassword()));
        //补全数据
        dtsAdmin.setAddTime(new Date());
        dtsAdmin.setUpdateTime(new Date());
        dtsAdmin.setDeleted(false);

        adminMapper.insert(dtsAdmin);
        return dtsAdmin;
    }

    @Override
    public int removeAdmin(int id) {
        int count = adminMapper.deleteById(id);
        return count;
    }

    @Override
    public int updateAdmin(DtsAdmin dtsAdmin) {
        int count = adminMapper.updateById(dtsAdmin);
        return count;
    }

    @Override
    public List<DtsAdmin> findAllAdmin() {
        return adminMapper.selectList(null);
    }

}
